import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:json_annotation/json_annotation.dart';

class ServiceOrder {
  final String reqId; // 提交工单时返回的id号，用于请求后续的业务数据
  final String orderNumber;
  final int type;
  final int source;
  final String contactPhone;
  final String customerName;
  final String serviceAddress;
  final String feedbackContent;
  final String modeifieTime;
  final String createTime;
  final String status;
  final String expectTime;

  final ServiceProduct product;

  final ServiceLocation location;

  ServiceOrder({
    required this.reqId,
    required this.orderNumber,
    required this.type,
    required this.source,
    required this.contactPhone,
    required this.customerName,
    required this.serviceAddress,
    required this.feedbackContent,
    required this.product,
    required this.location,
    required this.modeifieTime,
    required this.createTime,
    required this.status,
    required this.expectTime,
  });

  factory ServiceOrder.fromJson(Map<String, dynamic> json) {
    return _$ServiceOrderFromJson(json);
  }

  // 计算属性：服务类型描述
  String get serviceType {
    switch (type) {
      case 2:
        return "安装";
      case 1:
        return "报修";
      default:
        return "报修";
    }
  }

  Color get serviceTypeColor {
    switch (type) {
      case 2:
        return Color(0xFF6758D4);
      case 1:
        return Color(0xFFE37318);
      default:
        return Color(0xFFE37318);
    }
  }

  // 计算属性：来源描述
  String get sourceDescription {
    switch (source) {
      case 220:
        return "商城APP";
      default:
        return "其他来源";
    }
  }

  // 自定义解析逻辑
  static ServiceLocation _parseLocation(Map<String, dynamic> json) {
    return ServiceLocation(
      provinceName: json['new_province_id']?['name'] as String? ?? '',
      cityName: json['new_city_id']?['name'] as String? ?? '',
      countyName: json['new_county_id']?['name'] as String? ?? '',
    );
  }

  // 自定义解析逻辑
  static ServiceProduct _parseProduct(Map<String, dynamic> json) {
    return ServiceProduct(
      productId: json['casdon_product_id']?['id'] as String? ?? '',
      productName: json['casdon_product_id']?['name'] as String? ?? '',
    );
  }
}

class ServiceProduct {
  final String productId;
  final String productName;

  ServiceProduct({required this.productId, required this.productName});
}

class ServiceLocation {
  final String provinceName;
  final String cityName;
  final String countyName;

  ServiceLocation({
    required this.provinceName,
    required this.cityName,
    required this.countyName,
  });
}

class ResponseServiceOrderDataApi {
  @JsonKey(name: 'Entities')
  final List<ServiceOrder> entities; // 使用时，只取第一个。

  ResponseServiceOrderDataApi({required this.entities});

  factory ResponseServiceOrderDataApi.fromJson(Map<String, dynamic> json) {
    return _$ResponseServiceOrderDataApiFromJson(json);
  }
}

ServiceOrder _$ServiceOrderFromJson(Map json) => ServiceOrder(
  reqId: json['new_srv_workorderid'] as String? ?? '',
  orderNumber: json['new_name'] as String? ?? '',
  type: (json['new_type'] as num).toInt(),
  source: (json['new_source'] as num).toInt(),
  contactPhone: json['new_feedbacktel'] as String? ?? '',
  customerName: json['new_contact'] as String? ?? '',
  serviceAddress: json['new_address'] as String? ?? '',
  feedbackContent: json['new_memo'] as String? ?? '',
  createTime: convertTimeFomater(json["createdon"] as String? ?? ''),
  modeifieTime: convertTimeFomater(json["modifiedon"] as String? ?? ''),
  status: json['FormattedValues']['new_dealstatus'] as String? ?? '',
  expectTime: convertTimeFomater(
    json['FormattedValues']['casdon_expectarrivetime'] as String? ?? '',
  ),
  product: ServiceOrder._parseProduct(Map<String, dynamic>.from(json)),
  location: ServiceOrder._parseLocation(Map<String, dynamic>.from(json)),
);

ResponseServiceOrderDataApi _$ResponseServiceOrderDataApiFromJson(Map json) =>
    ResponseServiceOrderDataApi(
      entities: (json['Entities'] as List<dynamic>)
          .map(
            (e) => ServiceOrder.fromJson(Map<String, dynamic>.from(e as Map)),
          )
          .toList(),
    );

String convertTimeFomater(String timeStr) {
  if (timeStr.isEmpty) return '';

  try {
    // 解析UTC时间字符串（格式：2025-11-05 10:00:00）
    // 将字符串解析为本地时间（假设输入是UTC格式的字符串）
    final parsedDateTime = DateTime.parse(timeStr);
    // 将其视为UTC时间，然后转换为东八区时间（UTC+8）
    final utcDateTime = DateTime.utc(
      parsedDateTime.year,
      parsedDateTime.month,
      parsedDateTime.day,
      parsedDateTime.hour,
      parsedDateTime.minute,
      parsedDateTime.second,
    );
    // 转换为东八区时间（加8小时）
    final beijingDateTime = utcDateTime.add(const Duration(hours: 8));
    // 格式化为 yyyy-MM-dd HH:mm:ss
    return DateFormat('yyyy-MM-dd HH:mm:ss').format(beijingDateTime);
  } catch (e) {
    // 如果解析失败，返回原始字符串
    return timeStr;
  }
}
